﻿/* $RCSFile: Rating.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/Rating.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Diagnostics;

using Telerik.Web.UI;

using Trace2    =    System.Diagnostics.Trace;
using AddonNice.Helpers;
using System.Drawing;

namespace AddonNice.UI.WebControls
{
    /*
    <div style="width:748px;background-color: #dff3ff; border: 1px solid #c6e1f2;">
        <table style="width:748px;table-layout: fixed;">
            <tr>
                <td valign="top" style="padding-left: 15px; width: 130px;">
                    <br />
                    <asp:literal ID='litaverage' runat="server" Text="<%$ Resources:ADNCRM,CRMRATING_AVERAGE_RATING %>" />
                    <br />
                    <asp:Label ID="lblRating" runat="server" Text="0.0" Font-Size="50px" ForeColor="Gray" />
                    <br />
                    <br />
                </td>
                <td style="width: 348px">
                    <div style="padding-top: 30px">
                        <asp:Label ID="lblComments" runat="server" Font-Size="12px" ForeColor="Gray" Font-Italic="true" />
                    </div>
                </td>
                <td valign="top" style="width: 170px;">
                    <br />
                    <div style="float: right;">
                        <asp:literal ID='Literal1' runat="server" Text="<%$ Resources:ADNCRM,CRMRATING_RATE_THIS %>" />
                        <telerik:RadRating ID="RadRating1" runat="server" ItemCount="7" SelectionMode="Continuous" Precision="Exact"  />
                    </div>
                </td>
            </tr>
        </table>
    </div>
     */
    
    
    [ToolboxData("<{0}:Rating runat=server></{0}:Rating>")]
    public class Rating : CompositeControl
    {
        Table InternalTb                        =   null;
        Label RatingLabel               =   null;
        Label CommentsLabel             =   null;
        RadRating RadRating1            =   null;
        TableStyle _RatingTableStyle    =   null;

        /// <summary>
        /// The style to be applied to InternalTable.
        /// </summary>
		[
		Category("Style"),
		Description("The style to be applied to Internal Table"),
		DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
		PersistenceMode(PersistenceMode.InnerProperty)
		]
        public TableStyle RatingTableStyle
		{
			get 
			{
				if (_RatingTableStyle == null) 
				{
					_RatingTableStyle = new TableStyle();
					if (IsTrackingViewState)
						((IStateManager)_RatingTableStyle).TrackViewState();
				}
				return _RatingTableStyle;
			}
		}
        
        
        
        public Unit AverageWidth
        {
             get
             { 
                object ob                           =   ViewState["AverageWidth"];
                if ( ob != null )
                    return (Unit)ob;
                return Unit.Empty;
             }
             set { ViewState["AverageWidth"]        =   value; }
        }

        public Unit CommentsWidth
        {
             get
             { 
                object ob                           =   ViewState["CommentsWidth"];
                if ( ob != null )
                    return (Unit)ob;
                return Unit.Empty;
             }
             set { ViewState["CommentsWidth"]       =   value; }
        }

        public Unit RatingWidth
        {
             get
             { 
                object ob                           =   ViewState["RatingWidth"];
                if ( ob != null )
                    return (Unit)ob;
                return Unit.Empty;
             }
             set { ViewState["RatingWidth"]         =   value; }
        }

        public FontUnit LabelFontSize
		{
			get
			{
                object ob                           =   ViewState["LabelFontSize"];
                if ( ob != null )
                    return (FontUnit)ob;
                return FontUnit.Empty;
			}
			set
			{
				ViewState["LabelFontSize"] = value;
                if ( RatingLabel != null )
                    RatingLabel.Font.Size           =   value;
			}
		}
        
        public Color LabelForeColor
		{
			get
			{
                object ob                           =   ViewState["LabelForeColor"];
                if ( ob != null )
                    return (Color)ob;
                return Color.Empty;
			}
			set
			{
				ViewState["LabelForeColor"]         =   value;
                if ( RatingLabel != null )
                    RatingLabel.ForeColor           =   value;
			}
		}
        
        public FontUnit CommentsFontSize
		{
			get
			{
                object ob                           =   ViewState["CommentsFontSize"];
                if ( ob != null )
                    return (FontUnit)ob;
                return FontUnit.Empty;
			}
			set
			{
				ViewState["CommentsFontSize"] = value;
                if ( CommentsLabel != null )
                    CommentsLabel.Font.Size         =   value;
			}
		}
        
        public Color CommentsForeColor
		{
			get
			{
                object ob                           =   ViewState["CommentsForeColor"];
                if ( ob != null )
                    return (Color)ob;
                return Color.Empty;
			}
			set
			{
				ViewState["CommentsForeColor"]      =   value;
                if ( CommentsLabel != null )
                    CommentsLabel.ForeColor         =   value;
			}
		}

        public bool CommentsItalic
		{
			get
			{
                object ob                           =   ViewState["CommentsItalic"];
                if ( ob != null )
                    return (bool)ob;
                return false;
			}
			set
			{
				ViewState["CommentsItalic"]         =   value;
                if ( CommentsLabel != null )
                    CommentsLabel.Font.Italic       =   value;
			}
		}
        
        public bool ShowAverage
		{
			get
			{
                object ob                       =   ViewState["ShowAverage"];
                if ( ob != null )
                    return (bool)ob;
                return false;
			}
			set
			{
				ViewState["ShowAverage"]        =   value;
			}
		}

        public bool ShowComments
		{
			get
			{
                object ob                       =   ViewState["ShowComments"];
                if ( ob != null )
                    return (bool)ob;
                return false;
			}
			set
			{
				ViewState["ShowComments"]       =   value;
			}
		}
        
        /// <summary>
        /// Css class for the Rating Label
        /// </summary>
        public string LabelClass
		{
			get
			{
                object ob                       =   ViewState["LabelClass"];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
			}
			set
			{
				ViewState["LabelClass"]         =   value;
                if ( RatingLabel != null )
                    RatingLabel.CssClass        =   value;
			}
		}
        /// <summary>
        /// Text displayed in the rating label
        /// </summary>
        public string LabelText
		{
			get
			{
                object ob                       =   ViewState["LabelText"];
                if ( ob != null )
                    return (string)ob;
                return "0.0";
			}
			set
			{
				ViewState["LabelText"]          =   value;
                if ( RatingLabel != null )
                    RatingLabel.Text            =   value;
			}
		}
        
        public string OnClientLoad
		{
			get
			{
                object ob                       =   ViewState["OnClientLoad"];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
			}
			set
			{
				ViewState["OnClientLoad"]       =   value;
                if ( RadRating1 != null )
                    RadRating1.OnClientLoad     =   value;
			}
		}

        public string OnClientRated
		{
			get
			{
                object ob                       =   ViewState["OnClientRated"];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
			}
			set
			{
				ViewState["OnClientRated"]      =   value;
                if ( RadRating1 != null )
                    RadRating1.OnClientRated    =   value;
			}
		}

        public string OnClientRating
		{
			get
			{
                object ob                       =   ViewState["OnClientRating"];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
			}
			set
			{
				ViewState["OnClientRating"]     =   value;
                if ( RadRating1 != null )
                    RadRating1.OnClientRating   =   value;
			}
		}

        public int ItemCount
		{
			get
			{
                object ob                       =   ViewState["ItemCount"];
                if ( ob != null )
                    return (int)ob;
                return 8;
			}
			set
			{
				ViewState["ItemCount"]          =   value;
                if ( RadRating1 != null )
                    RadRating1.ItemCount        =   value;
			}
		}

        public RatingSelectionMode SelectionMode
		{
			get
			{
                object ob                       =   ViewState["SelectionMode"];
                if ( ob != null )
                    return (RatingSelectionMode )ob;
                return RatingSelectionMode.Continuous;
			}
			set
			{
				ViewState["SelectionMode"]      =   value;
                if ( RadRating1 != null )
                    RadRating1.SelectionMode    =   value;
			}
		}

        public RatingPrecision Precision
		{
			get
			{
                object ob                           =   ViewState["Precision"];
                if ( ob != null )
                    return (RatingPrecision )ob;
                return RatingPrecision.Exact;
			}
			set
			{
				ViewState["SelectionMode"]          =   value;
                if ( RadRating1 != null )
                    RadRating1.Precision            =   value;
			}
		}

        public Orientation RatingOrientation
		{
			get
			{
                object ob                           =   ViewState["Orientation"];
                if ( ob != null )
                    return (Orientation)ob;
                return Orientation.Horizontal;
			}
			set
			{
				ViewState["Orientation"]            =   value;
                if ( RadRating1 != null )
                    RadRating1.Orientation          =   value;
			}
		}
        
        public bool ReadOnly
		{
			get
			{
                object ob                           =   ViewState["ReadOnly"];
                if ( ob != null )
                    return (bool)ob;
                return false;
			}
			set
			{
				ViewState["ReadOnly"]               =   value;
                if ( RadRating1 != null )
                    RadRating1.ReadOnly             =   value;
			}
		}

        public bool IsDirectionReversed
		{
			get
			{
                object ob                           =   ViewState["IsDirectionReversed"];
                if ( ob != null )
                    return (bool)ob;
                return false;
			}
			set
			{
				ViewState["IsDirectionReversed"]    =   value;
                if ( RadRating1 != null )
                    RadRating1.IsDirectionReversed  =   value;
			}
		}

        public override void DataBind()
        {
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine("[V]Rating DataBind BEG.", WebControlsTraceSwitch.Sw.Info);
            OnDataBinding(EventArgs.Empty);
            EnsureChildControls();
            DataBindChildren();
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine("[V]Rating DataBind END.", WebControlsTraceSwitch.Sw.Info);
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }
        
        /// <summary>
        /// Ctor
        /// </summary>
        public Rating()
		{
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine("[V]Rating Ctor Called.", WebControlsTraceSwitch.Sw.Info);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Rating Render BEG.",WebControlsTraceSwitch.Sw.Info);
            if ( DesignMode )
                EnsureChildControls();
            try
            {
                base.Render(writer);
            }
            catch (Exception ex)
            {
                if ( WebControlsTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]Rating Render ex: {0}",ex),WebControlsTraceSwitch.Sw.Info);
                throw;
            }
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Rating Render END.",WebControlsTraceSwitch.Sw.Info);
        }

        protected override void CreateChildControls()
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Rating CreateChildControls BEG ShowAverage: {0}, ShowComments: {1}", ShowAverage,ShowComments),WebControlsTraceSwitch.Sw.Info);
            ClearChildViewState();
            Controls.Clear();
            //Style.Add(HtmlTextWriterStyle.Margin,"5px");// to not have right side under tablesettings right side
            InternalTb			                    =	new Table();
			InternalTb.Width				        =	new Unit("100%");
			TableRow rw			                    =	new TableRow();
            TableCell c			                    =	null;
			
            // Label Column (-> Average Rating )
            if ( ShowAverage )
            {
                c			                        =	new TableCell();
			    c.VerticalAlign                     =   VerticalAlign.Top;
                if ( AverageWidth != Unit.Empty )
			        c.Style.Add(HtmlTextWriterStyle.Width,AverageWidth.ToString());
			    Literal litaverage	                =	new Literal();
                litaverage.Text                     =   LocalizeHelper.Localize("CRMRATING_AVERAGE_RATING","AverageRating RatingAnswerCrmID");
                c.Controls.Add(litaverage);
                c.Controls.Add(new LiteralControl("<br />"));
                RatingLabel                         =   new Label();
                RatingLabel.ID                      =   "RatingLabel";
                RatingLabel.CssClass                =   LabelClass;
                if ( LabelFontSize != FontUnit.Empty )
                    RatingLabel.Font.Size           =   LabelFontSize;
                if ( LabelForeColor != Color.Empty )
                    RatingLabel.ForeColor           =   LabelForeColor;
                c.Controls.Add(RatingLabel);
                c.Controls.Add(new LiteralControl("<br />"));
                c.Controls.Add(new LiteralControl("<br />"));
                rw.Cells.Add(c);
            }            
            // Comments column ( From xxx-> Comment....
            if ( ShowComments )
            {
                c			                        =	new TableCell();
			    c.VerticalAlign                     =   VerticalAlign.Top;
                if ( CommentsWidth != Unit.Empty )
			        c.Style.Add(HtmlTextWriterStyle.Width,CommentsWidth.ToString());
                HtmlGenericControl  divComment      =   new HtmlGenericControl("div");
                divComment.Style.Add(HtmlTextWriterStyle.PaddingTop,"30px");
                CommentsLabel                       =    new Label();
                CommentsLabel.ID                    =   "lblComments";
                if ( CommentsFontSize != FontUnit.Empty )
                    CommentsLabel.Font.Size         =   CommentsFontSize;
                if ( CommentsForeColor != Color.Empty )
                    CommentsLabel.ForeColor         =   CommentsForeColor;
                CommentsLabel.Font.Italic           =   CommentsItalic;
                divComment.Controls.Add(CommentsLabel);
                c.Controls.Add(divComment);
                rw.Cells.Add(c);
            }
            // Rating column (Rate This + stars)
            c			                            =	new TableCell();
		    c.VerticalAlign                         =   VerticalAlign.Top;
            if ( RatingWidth != Unit.Empty )
			    c.Style.Add(HtmlTextWriterStyle.Width,RatingWidth.ToString());
            c.Controls.Add(new LiteralControl("<br />"));
            HtmlGenericControl  divrating           =   new HtmlGenericControl("div");
            divrating.Style.Add("float","right");
			Literal litrat	                        =	new Literal();
            litrat.Text                             =   LocalizeHelper.Localize("CRMRATING_RATE_THIS","Rate this");
            c.Controls.Add(litrat);
            RadRating1                              =   new RadRating();
            RadRating1.ID                           =   "RadRating1";
            RadRating1.ItemCount                    =   ItemCount;
            RadRating1.SelectionMode                =   SelectionMode;
            RadRating1.Precision                    =   Precision;
            RadRating1.IsDirectionReversed          =   IsDirectionReversed;
            RadRating1.Orientation                  =   RatingOrientation;
            RadRating1.ReadOnly                     =   ReadOnly;
            RadRating1.OnClientLoad                 =   OnClientLoad;
            RadRating1.OnClientRated                =   OnClientRated;
            RadRating1.OnClientRating               =   OnClientRating;
            c.Controls.Add(RadRating1);
            
            rw.Cells.Add(c);
            InternalTb.Rows.Add(rw);
            Controls.Add(InternalTb);

            ChildControlsCreated                    =   true;
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]Rating CreateChildControls END.",WebControlsTraceSwitch.Sw.Info);
        }

        #region events and handlers

        /// Move event raised when a move is performed
		public event EventHandler Rate;

		protected virtual void OnRate(EventArgs e)
		{
			if (Rate != null)
			{
				Rate(this, e);
			}
		}
        
        void RadRating1_Rate(object sender,EventArgs e)
        {
            OnRate(e);
        }
        #endregion events and handlers
        
        
        private void PrepareControlHierarchy()
        {
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Rating PrepareControlHierarchy BEG ChildControlsCreated: {0}", ChildControlsCreated),WebControlsTraceSwitch.Sw.Info);
            EnsureChildControls();

            if (RatingTableStyle.IsEmpty)
            {
                InternalTb.Style.Add("table-layout","fixed");
            }
		    else InternalTb.MergeStyle(RatingTableStyle);
            if ( WebControlsTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Rating PrepareControlHierarchy END.",WebControlsTraceSwitch.Sw.Info);
        }

        #region IStateManager

        /// <summary>
        /// This member overrides Control.LoadViewState
        /// </summary>
		protected override void LoadViewState(object savedState) 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Rating LoadViewState BEG.",PageTraceSwitch.Sw.Info);
			// Customize state management to handle saving state of contained objects.
			if (savedState != null) 
			{
				object[] myState    =   (object[])savedState;

				if (myState[0] != null)
					base.LoadViewState(myState[0]);
				if (myState[1] != null)
					((IStateManager)_RatingTableStyle).LoadViewState(myState[1]);
			}
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Rating LoadViewState END.",PageTraceSwitch.Sw.Info);
		}
        
        /// <summary>
        /// This member overrides Control.SaveViewState
        /// </summary>
		protected override object SaveViewState() 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Rating SaveViewState BEG.",PageTraceSwitch.Sw.Info);
			// Customized state management to handle saving state of contained objects  such as styles.
			object baseState                =   base.SaveViewState();
			object RatingTableStyleState    =   (_RatingTableStyle != null) ? ((IStateManager)_RatingTableStyle).SaveViewState() : null;

			object[] myState                =   new object[2];
			myState[0]                      =   baseState;
			myState[1]                      =   RatingTableStyleState;
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Rating SaveViewState END.",PageTraceSwitch.Sw.Info);
			return myState;
		}

        /// <summary>
        /// This member overrides Control.TrackViewState.
        /// </summary>
		protected override void TrackViewState() 
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]Rating TrackViewState BEG.",PageTraceSwitch.Sw.Info);
			// Customized state management to handle saving state of contained objects such as styles.
			base.TrackViewState();

			if (_RatingTableStyle!= null)
				((IStateManager)_RatingTableStyle).TrackViewState();
		}

        #endregion IStateManager 
        
        protected override void OnPreRender(EventArgs e)
        {
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]Rating OnPreRender BEG IsPostBack: {0}", Page.IsPostBack), WebControlsTraceSwitch.Sw.Info);
            base.OnPreRender(e);
            PrepareControlHierarchy();
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]Rating OnPreRender END.", WebControlsTraceSwitch.Sw.Info);
        }

        protected override void OnInit(EventArgs e)
        {
            EnsureChildControls();
            RadRating1.Rate     +=  new EventHandler(RadRating1_Rate);
            base.OnInit(e);
        }
   }
}
